
import jwt
from django.http import JsonResponse
from django.conf import settings

from rest_framework.response import Response
from rest_framework import status
from common.constant.ResultConstant import ResultEnum
import logging

logger = logging.getLogger('mylogger')


class JwtMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 获取请求路径
        path = request.path

        path_segments = path.strip('/').split('/')
        logger.info('请求路径： ' + path)

        # 获取路径的最后一部分
        last_segment = path_segments[-1]

        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            token = auth_header.split(' ')[1] if ' ' in auth_header else None

            # 进行 JWT 验证
            if token:
                try:
                    # 解码 JWT 令牌
                    decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
                    # 在这里，你可以根据需要检查令牌中的声明
                    # 例如，检查过期时间 (exp)、用户身份等
                    # print(decoded_token)

                    # 将解码后的令牌信息存储在请求对象中，以便在视图中访问
                    request.jwt_payload = decoded_token

                except jwt.ExpiredSignatureError as e:
                    # 处理令牌过期错误
                    return JsonResponse(ResultEnum.TOKEN_EXPIRED_419)
                except jwt.DecodeError as e:
                    # 处理其他错误
                    return JsonResponse(ResultEnum.INVALID_TOKEN_401)
                except jwt.InvalidTokenError:
                    # 处理无效令牌错误

                    return JsonResponse(ResultEnum.INVALID_TOKEN_401)
        else:
            # 在请求到达视图之前执行的代码
            if last_segment != 'login' and last_segment != 'register' and last_segment != 'test' and path_segments[0] != '' and \
                    path_segments[0] != 'admin':
                return JsonResponse(ResultEnum.INVALID_TOKEN_401, status=status.HTTP_401_UNAUTHORIZED)

        # 请求继续传递给下一个中间件或视图
        response = self.get_response(request)

        # 在请求离开视图之后执行的代码

        return response
